using System.Timers;
using Timer = System.Timers.Timer;

namespace MultiAgentsClient.Service;

public abstract class TimedDisposableBase : IDisposable
{
    private Timer? timer;
    private bool isDisposed;

    public event Action? OnTaskCancelled;

    protected TimedDisposableBase(double timeoutMilliseconds)
    {
        timer = new Timer(timeoutMilliseconds);
        timer.Elapsed += TimerElapsed;
        timer.AutoReset = false;
        timer.Start();
    }

    private void TimerElapsed(object? sender, ElapsedEventArgs e)
    {
        CancelTask();
    }

    private void CancelTask()
    {
        OnTaskCancelled?.Invoke();
        Dispose();
    }

    protected virtual void Dispose(bool disposing)
    {
        if (isDisposed)
            return;

        if (disposing)
        {
            if (timer != null)
            {
                timer.Stop();
                timer.Dispose();
                timer = null;
            }
        }

        isDisposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~TimedDisposableBase()
    {
        Dispose(false);
    }
}
